extends Node2D
class_name BaseGrid
signal on_trace_log(cell : BaseCell,is_check : bool)

@export var open_debug : bool
@export var cell_size : Vector2 = Vector2(128,128)
const BASE_CELL_PRE = preload("res://grid/base_cell.tscn")
const SPACE : Vector2 = Vector2(4.0,4.0)
var grid_xy : Vector2i = Vector2i.ZERO
var cells : Dictionary
var note_xy : Dictionary

func _ready() -> void:
	_init_pos()
	_create_grid()

func _init_pos() -> void :
	var base_cell = BASE_CELL_PRE.instantiate()
	base_cell.item_size = cell_size
	base_cell.queue_free()
	global_position.x -= ((grid_xy.x - 1) * cell_size.x + SPACE.x * (grid_xy.x - 1))/ 2.0
	global_position.y -= ((grid_xy.y - 1) * cell_size.y + SPACE.y * (grid_xy.y - 1))/ 2.0

func _create_grid() :
	for y in grid_xy.y :
		for x in grid_xy.x :
			var cell = BASE_CELL_PRE.instantiate()
			cell.item_size = cell_size
			cell._save_xy(x,y)
			cell.type = cells.get(Vector2i(x,y),-1)
			cell.is_debug = open_debug
			cell.on_click_entered.connect(func(_cell):on_trace_log.emit(_cell,true))
			cell.on_move_entered.connect(func(_cell):on_trace_log.emit(_cell,false))
			_add_cell(cell,x,y)

func _add_cell(base_cell,x=0,y=0) -> void :
	base_cell.position = Vector2(x * base_cell.item_size.x,y * base_cell.item_size.y) + Vector2(SPACE.x * x,SPACE.y * y)
	add_child(base_cell)

func _get_cell_by_pos(pos : Vector2) -> void :
	var _local_pos = to_local(pos)

func _get_only_cell_by_type(type : GlobelEnum.CellType, index : int = 0) -> BaseCell :
	for child in get_children() :
		if is_same(child.type,type) :
			return child
	return get_child(index)

func _get_target_dir(ori : BaseCell, target : BaseCell) -> Vector2 :
	var target_cell = target.get_index()
	var ori_cell = ori.get_index()
	if abs(target_cell - ori_cell) == 1 : return Vector2(target_cell - ori_cell,0)
	if abs(target_cell - ori_cell) == grid_xy.x : return Vector2(0,1 if target_cell>ori_cell else -1)
	return Vector2.ZERO
